#include "stringlistmodel.h"

StringListModel::StringListModel(const QStringList &strings, QObject *parent):
    QAbstractListModel(parent),StringList(strings)
{ }

int StringListModel::rowCount(const QModelIndex &parent) const
{
    return StringList.size();
}

QVariant StringListModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid()){
        return QVariant();
    }

    if(index.row()>= StringList.size()){
        return QVariant();
    }

    if(role==Qt::DisplayRole){
        return StringList.at(index.row());
    }else{
        return QVariant();
    }
}

QVariant StringListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole){
        return QVariant();
    }
    if(orientation == Qt::Horizontal){
        return QString("Column %1").arg(section);
    }else{
        return QString("Row %1").arg(section);
    }
}


Qt::ItemFlags  StringListModel::flags(const QModelIndex& index) const{
    //索引无效可以接受放入操作
    if(!index.isValid())
        return Qt::ItemIsEnabled ;
    //索引有效，可以接受拖拽和放入操作
    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

bool StringListModel::setData(const QModelIndex& index,
                              const QVariant &value, int role ){
    if(index.isValid() && role == Qt::EditRole){
        StringList.replace(index.row(), value.toString());
        emit dataChanged(index, index);
        return true;
    }

    return false;
}

bool StringListModel::insertRows(int position, int rows,
                                 const QModelIndex & index ){
    beginInsertRows(index, position, position + rows -1);
    for(int row = 0; row < rows; ++ row){
        StringList.insert(position, "");
    }
    endInsertRows();
    return true;
}
bool StringListModel::removeRows(int position, int rows,
                                 const QModelIndex & index ){
    beginRemoveRows(index, position, position+ rows-1);
    for(int row=0; row < rows; ++ row){
        StringList.removeAt(position);
    }
    endRemoveRows();
    return true;
}
